package com.jgssp.ad.sdk.topon.adapter;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.ViewGroup;

import com.anythink.core.api.ATAdConst;
import com.anythink.core.api.ATBiddingListener;
import com.anythink.core.api.ATBiddingResult;
import com.anythink.core.api.MediationInitCallback;
import com.anythink.splashad.unitgroup.api.CustomSplashAdapter;

import java.util.Map;
import java.util.UUID;

import cn.jiguang.jgssp.ad.ADJgSplashAd;
import cn.jiguang.jgssp.ad.data.ADJgAdInfo;
import cn.jiguang.jgssp.ad.error.ADJgError;
import cn.jiguang.jgssp.ad.listener.ADJgSplashAdListener;

/**
 * @author songzi
 * @date 2021/12/6
 */
public class SplashAdapter extends CustomSplashAdapter {
    private String slotId;
    private ADJgSplashAd splashAd;
    private boolean isAgreePrivacyStrategy;
    private boolean isBidding;
    private ADJgAdInfo mSplashAdInfo;
    private ATBiddingListener biddingListener;

    @Override
    public void loadCustomNetworkAd(final Context context, Map<String, Object> serverExtra, Map<String, Object> localExtra) {
        if (serverExtra.containsKey("slot_id")) {
            slotId = (String) serverExtra.get("slot_id");
        }
        InitManager.getInstance().
                initSDK(context, serverExtra, isAgreePrivacyStrategy, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {
                        String name = Thread.currentThread().getName();
                        Log.e("wsong", "name = " + name);
                        startLoad(context);
                    }

                    @Override
                    public void onFail(String msg) {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1001", msg);
                        }
                    }
                });
    }

    @Override
    public boolean startBiddingRequest(final Context context, Map<String, Object> serverExtra, Map<String, Object> localExtra, ATBiddingListener biddingListener) {
        this.isBidding = true;
        this.biddingListener = biddingListener;
        if (serverExtra.containsKey("slot_id")) {
            slotId = (String) serverExtra.get("slot_id");
        }

        InitManager.getInstance().
                initSDK(context, serverExtra, isAgreePrivacyStrategy, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {
                        startLoad(context);
                    }

                    @Override
                    public void onFail(String msg) {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1001", msg);
                        }
                    }
                });
        return true;
    }

    private void startLoad(final Context context) {
        postOnMainThread(new Runnable() {
            @Override
            public void run() {

                if (!(context instanceof Activity)) {
                    if (isBidding) {
                        if (biddingListener != null) {
                            biddingListener.onC2SBiddingResultWithCache(
                                    ATBiddingResult.fail("context is null or context must be Activity"),
                                    null);
                        }
                    } else {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1", "context is null or context must be Activity");
                        }
                    }
                    return;
                }

                splashAd = new ADJgSplashAd(context);
                splashAd.setListener(new ADJgSplashAdListener() {
                    @Override
                    public void onAdExpose(ADJgAdInfo adJgAdInfo) {
                        if (mImpressionListener != null) {
                            mImpressionListener.onSplashAdShow();
                        }
                    }

                    @Override
                    public void onAdClick(ADJgAdInfo adJgAdInfo) {
                        if (mImpressionListener != null) {
                            mImpressionListener.onSplashAdClicked();
                        }
                    }

                    @Override
                    public void onAdClose(ADJgAdInfo adJgAdInfo) {
                        if (mImpressionListener != null) {
                            mImpressionListener.onSplashAdDismiss();
                        }
                    }

                    @Override
                    public void onAdFailed(ADJgError error) {
                        if (isBidding) {
                            if (biddingListener != null) {
                                biddingListener.onC2SBiddingResultWithCache(
                                        ATBiddingResult.fail(error.getError())
                                        , null
                                );
                            }
                        } else {
                            if (mLoadListener != null) {
                                mLoadListener.onAdLoadError(
                                        "" + error.getCode()
                                        , "" + error.getError()
                                );
                            }
                        }
                    }

                    @Override
                    public void onAdReceive(ADJgAdInfo adInfo) {
                        mSplashAdInfo = adInfo;
                        if (isBidding) {
                            if (biddingListener != null) {
                                if (adInfo != null && adInfo.getECPM() > 0) {
                                    //用于标识此次竞价的唯一ID，可使用UUID或者时间戳
                                    String token = UUID.randomUUID().toString();
                                    biddingListener.onC2SBiddingResultWithCache(
                                            ATBiddingResult.success(
                                                    adInfo.getECPM()
                                                    , token
                                                    , null
                                                    , ATAdConst.CURRENCY.RMB)
                                            , null);
                                } else {
                                    biddingListener.onC2SBiddingResultWithCache(
                                            ATBiddingResult.fail("adInfo is null"),
                                            null);
                                }
                            }
                        } else {
                            if (mLoadListener != null) {
                                mLoadListener.onAdCacheLoaded();
                            }
                        }
                    }

                    @Override
                    public void onAdSkip(ADJgAdInfo adJgAdInfo) {
                        if (mImpressionListener != null) {
                            mImpressionListener.onSplashAdDismiss();
                        }
                    }

                    @Override
                    public void onADTick(long l) {

                    }

                    @Override
                    public void onReward(ADJgAdInfo adJgAdInfo) {

                    }
                });
                Log.e("wsong", "loadOnly = " + getNetworkPlacementId());
                splashAd.loadOnly(getNetworkPlacementId());
            }
        });

    }

    @Override
    public void show(Activity activity, final ViewGroup container) {
        postOnMainThread(new Runnable() {
            @Override
            public void run() {
                if (splashAd != null && mSplashAdInfo != null) {
                    splashAd.showSplash(container);
                }
            }
        });
    }

    @Override
    public String getNetworkPlacementId() {
        return slotId;
    }

    @Override
    public String getNetworkSDKVersion() {
        return InitManager.getInstance().getNetworkVersion();
    }

    @Override
    public String getNetworkName() {
        return InitManager.getInstance().getNetworkName();
    }

    @Override
    public boolean isAdReady() {
        return mSplashAdInfo != null;
    }

    /**
     * @param context
     * @param isConsent   用户是否授权
     * @param isEUTraffic 是否是欧盟地区
     * @return
     */
    @Override
    public boolean setUserDataConsent(Context context, boolean isConsent, boolean isEUTraffic) {
        isAgreePrivacyStrategy = isConsent;
        return super.setUserDataConsent(context, isConsent, isEUTraffic);
    }

    @Override
    public void destory() {
        if (splashAd != null) {
            splashAd.release();
            splashAd = null;
        }

        biddingListener = null;
    }
}
